<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.orgduty_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="success"
                   size="small"
                   plain
                   v-if="permission.orgduty_import"
                   icon="el-icon-upload2"
                   @click="handleImport">导入
        </el-button>
        <el-button type="warning"
                   size="small"
                   plain
                   v-if="permission.orgduty_export"
                   icon="el-icon-download"
                   @click="handleExport">导出
        </el-button>
      </template>
    </avue-crud>
    <el-dialog title="应急组织职责数据导入"
               append-to-body
               :visible.sync="excelBox"
               width="555px">
      <avue-form :option="excelOption" v-model="excelForm"
                 :upload-before="beforeUpload"
                 :upload-after="uploadAfter"
                 :upload-error="uploadError"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/emer/orgduty";
  import {mapGetters} from "vuex";
  import {getToken} from "@/util/auth";
  import {getFzrLinkInfo} from "@/api/mmhi/prod_unit";

  export default {
    data() {
      return {
        excelBox: false,
        excelForm: {},
        excelOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '模板上传',
              prop: 'excelFile',
              type: 'upload',
              drag: true,
              loadText: '模板上传中，请稍等',
              showFileList: false,
              span: 24,
              propsHttp: {
                res: 'data'
              },
              tip: '请上传 .xls,.xlsx 标准格式文件',
              action: "/api/emerOrgDuty/import"
            },
            {
              label: '模板下载',
              prop: 'excelTemplate',
              formslot: true,
              span: 24,
            }
          ]
        },
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "企业名称",
              prop: "qymc",
              align: "center",
              maxlength:100,
              search:true,
              rules: [{
                required: true,
                message: "请输入企业名称",
                trigger: "blur"
              }]
            },
            {
              label: "组织名称",
              prop: "zzmc",
              align: "center",
              maxlength:100,
              rules: [{
                required: true,
                message: "请输入组织名称",
                trigger: "blur"
              }]
            },
            {
              label: "组织负责人",
              prop: "zzfzr",
              align: "center",
              width:90,
              labelWidth:100,
              maxlength:100,
              type: "select",
              dicUrl: "/api/prodUnitManage/bladeProdUnit/getFzrList",
              props: {
                value: "realName"
              },
              rules: [{
                required: true,
                message: "请输入组织负责人",
                trigger: "blur"
              }]
            },
            {
              label: "组织负责人电话",
              prop: "zzfzrdh",
              width:120,
              labelWidth:120,
              align: "center",
              maxlength:11,
              disabled:true
            },
            {
              label: "组织联系人",
              prop: "zzlxr",
              width:90,
              align: "center",
              labelWidth:100,
              maxlength:100,
              type: "select",
              dicUrl: "/api/prodUnitManage/bladeProdUnit/getFzrList",
              props: {
                value: "realName"
              },
              rules: [{
                required: true,
                message: "请输入组织联系人",
                trigger: "blur"
              }]
            },
            {
              label: "组织联系人电话",
              prop: "zzlxrdh",
              width:120,
              align: "center",
              labelWidth:120,
              maxlength:11,
              disabled:true
            },
            {
              label: "组织应急职责",
              prop: "zzyjzz",
              align: "center",
              labelWidth:110,
              maxlength:100,
              rules: [{
                required: true,
                message: "请输入组织应急职责",
                trigger: "blur"
              }]
            },
            {
              label: "备注",
              prop: "bz",
              align: "center",
              type: "textarea",
              span:24,
              maxlength:2000,
              rules: [{
                required: false,
                message: "请输入备注",
                trigger: "blur"
              }]
            }
          ]
        },
        data: []
      };
    },
    watch: {
      'form.zzfzr':{
        handler(val){
          if(val!='' && val!=undefined && val!=null){
            getFzrLinkInfo(val).then(res=>{
              this.form.zzfzrdh = res.data.data[0].phone;
            });
          }
        },
        immediate: true
      },
      'form.zzlxr':{
        handler(val){
          if(val!='' && val!=undefined && val!=null){
            getFzrLinkInfo(val).then(res=>{
              this.form.zzlxrdh = res.data.data[0].phone;
            });
          }
        },
        immediate: true
      }
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.orgduty_add, false),
          viewBtn: this.vaildData(this.permission.orgduty_view, false),
          delBtn: this.vaildData(this.permission.orgduty_delete, false),
          editBtn: this.vaildData(this.permission.orgduty_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      // 导入前判断
      beforeUpload(file, done, loading) {
        this.uploadFailed = false;
        var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
        const extension = testmsg === 'xls'
        const extension2 = testmsg === 'xlsx'
        if(!extension && !extension2) {
          this.$message.warning('请上传 .xls,.xlsx 标准格式文件!');
          loading()
        } else {
          done()
        }
      },
      // 导入成功后1
      uploadAfter1() {
        this.excelBox = false;
        this.$message.success("上传成功");
        this.page.currentPage = 1;
        this.onLoad(this.page);
      },
      // 导入成功后
      uploadAfter(res, done) {
        done();
        if(this.uploadFailed === true) {
          return;
        }
        this.uploadAfter1()
      },
      // 导入失败后
      uploadError(error, column) {
        console.log(error,column);
        this.uploadFailed = true;
      },
      //导出应急组织职责
      handleExport() {
        this.$confirm("是否导出应急组织职责数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          let zbmc = this.query.zbmc !== undefined && this.query.zbmc !== "" && this.query.zbmc !== null ? this.query.zbmc : "";
          window.open(`/api/emerOrgDuty/export?${this.website.tokenHeader}=${getToken()}&zbmc=${zbmc}`);
        });
      },
      //打开导入弹窗
      handleImport() {
        this.excelForm=[]
        this.excelBox = true;
      },
      //导出摸板
      handleTemplate() {
        window.open(`/api/emerOrgDuty/export-template?${this.website.tokenHeader}=${getToken()}`);
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style lang="scss">
  .avue-crud__dialog {
  .el-dialog__body {
  .el-form-item__label {
    width: 130px !important;
  }

  .avue-form__row {
  .el-form-item__content {
    margin-left: 130px !important;
  }
  }
  }
  }
</style>
